#include "flash.h"

uint16_t FLASH_ReadHalfWord(uint32_t faddr)
{
    return *(__IO uint16_t *)faddr;
}
//从指定地址开始读出指定长度的数据
// ReadAddr:起始地址
// pBuffer:数据指针
// NumToWrite:半字(16位)数
void Flash_ReadData(uint32_t ReadAddr, uint16_t *pBuffer, uint16_t NumToRead)
{
    uint16_t i;
    for (i = 0; i < NumToRead; i++)
    {
        pBuffer[i] = FLASH_ReadHalfWord(ReadAddr); //读取2个字节.
        ReadAddr += 2;                             //偏移2个字节.
    }
}

void Flash_WriteData(uint32_t addr, uint16_t *data, uint16_t Size)
{
    // 1、解锁FLASH
    HAL_FLASH_Unlock();

    // 2、擦除FLASH
    //初始化FLASH_EraseInitTypeDef
    FLASH_EraseInitTypeDef f;
    f.TypeErase   = FLASH_TYPEERASE_PAGES;
    f.PageAddress = addr;
    f.NbPages     = 1;
    //设置PageError
    uint32_t PageError = 0;
    //调用擦除函数
    HAL_FLASHEx_Erase(&f, &PageError);

    // 3、对FLASH烧写
    uint16_t TempBuf = 0;
    for (uint16_t i = 0; i < Size; i++)
    {
        TempBuf = *(data + i);
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, addr + i * 2, TempBuf);
    }

    // 4、锁住FLASH
    HAL_FLASH_Lock();
}
